#include "deviceutils.h"

#include <QProcess>
#include <QtCore/qmath.h>
#include "QApplication"
#include "QDebug"
#include "QRegExp"
#include "event/logevent.h"
#include "QSettings"

QString DeviceUtils::getMachineCode()
{
    QString boardNum = getBaseboardNum();
    QString cpuId = getCPUID();
    QString diskNum = getDiskNum();

    int boardNumSize = boardNum.size();
    int cpuIdSize = cpuId.size();
    int diskNumSize = diskNum.size();

    int maxLength;
    if(boardNumSize >= cpuIdSize){
        maxLength = boardNumSize;
    }else{
        maxLength = cpuIdSize;
    }

    if(maxLength <= diskNumSize){
        maxLength = diskNumSize;
    }
    QString result;
    for(int i = 0 ; i < maxLength ;i++){
        if(i < boardNumSize){
            result.append(boardNum.at(i));
        }

        if(i < cpuIdSize){
            result.append(cpuId.at(i));
        }

        if(i < diskNumSize){
            result.append(diskNum.at(i));
        }
    }
    return result.mid(0, 32);
}

void DeviceUtils::sendLog(QWidget *eidt, QString log)
{
    LogEvent *rolesLog1 = new LogEvent(log);
    QApplication::postEvent(eidt, rolesLog1);
}

QString DeviceUtils::getMachineGuid()
{
    QSettings setting("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography", QSettings::NativeFormat);
    return setting.value("MachineGuid","").toString().replace("-","").toUpper();
}

QString DeviceUtils::getWMIC(const QString &cmd)
{
    //获取cpu名称：wmic cpu get Name
    //获取cpu核心数：wmic cpu get NumberOfCores
    //获取cpu线程数：wmic cpu get NumberOfLogicalProcessors
    //查询cpu序列号：wmic cpu get processorid
    //查询主板序列号：wmic baseboard get serialnumber
    //查询BIOS序列号：wmic bios get serialnumber
    //查看硬盘：wmic diskdrive get serialnumber
    QProcess p;
    p.start(cmd);
    p.waitForFinished();
    QString result = QString::fromLocal8Bit(p.readAllStandardOutput());
    QStringList list = cmd.split(" ");
    result = result.remove(list.last(), Qt::CaseInsensitive);
    result = result.replace(" ", "");
    result = result.replace("\r", "");
    result = result.replace("\n", "");
    result = result.simplified();
    return result;
}

QString DeviceUtils::getCPUID()
{
    return getWMIC("wmic cpu get processorid");
}

QString DeviceUtils::getDiskNum()
{
    return getWMIC("wmic diskdrive get serialnumber");
}

QString DeviceUtils::getBaseboardNum()
{
    return getWMIC("wmic baseboard get serialnumber");

}

bool DeviceUtils::checkString(QString string,QString reg){
    QRegExp rx(reg);
    return string.contains(rx);
}
